import BridgePlugin from './plugins/bridge';
import FalconBridgePlugin from './plugins/falconBridge';
import MessagePlugin from './plugins/message';
import { getGphoneVersion, getIphoneVersion, getParam, getPlatform } from './utils';

const Identifier = '__whistle.bridge__';

interface IConfig {
  baseUrl: string;
  sendDelay: number;
  name: string;
}

const defaultConfig: IConfig = {
  baseUrl: '//local.whistlejs.com/plugin.bridge',
  sendDelay: 1000,
  name: Date.now().toString(32),
};

class WhistleBridge {
  root: HTMLElement | null = null;

  config: IConfig | null = null;

  status: Record<string, any> = {
    createTime: Date.now(),
    pagePath: location.href,
    title: document.title,
    params: getParam(),
    platform: getPlatform(),
    gphoneVersion: getGphoneVersion(),
    iphoneVersion: getIphoneVersion(),
  };

  bridgePluginIns: any = null;

  messagePluginIns: any = null;

  static plugins: any[] = [];

  static instance: WhistleBridge | null = null;

  constructor(init: Partial<IConfig> = {}) {
    if (WhistleBridge.instance) {
      console.warn('Cannot initialize WhistleBridge multiple times');
      return WhistleBridge.instance;
    }

    WhistleBridge.instance = this;
    // @ts-ignore
    window[Identifier] = this;
    // @ts-ignore
    window.WhistleBridge = WhistleBridge;

    this.config = Object.freeze(Object.assign({}, defaultConfig, init));
    this.triggerPlugins('onInit', { root: this });
  }

  static addPlugin(pluginIns: any) {
    WhistleBridge.plugins.push(pluginIns);
  }

  private triggerPlugins(lifecycle: any, args: any) {
    const plugins = WhistleBridge.plugins;
    plugins.forEach(plugin => plugin[lifecycle]?.(args));
  }

  public setBridgePlugin(bridgePlugin: any) {
    this.bridgePluginIns = bridgePlugin;
    this.triggerPlugins('onBridged', { bridgePlugin });
  }

  public setMessagePlugin(messagePlugin: any) {
    this.messagePluginIns = messagePlugin;
    this.triggerPlugins('onConnected', { messagePlugin });
  }
}

WhistleBridge.addPlugin(new BridgePlugin());
WhistleBridge.addPlugin(new MessagePlugin());
// WhistleBridge.addPlugin(new FalconBridgePlugin());

export default WhistleBridge;
